package com.example.config;

import com.example.filter.SecurityJwtAuthenticationFilter;
import com.example.security.handler.*;
import com.example.security.custom.CustomAuthenticationProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.CorsConfigurationSource;

import java.util.Arrays;

/**
 * Security 配置
 *
 * @author 朽
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    public static final String LOGIN_URI = "/user/login";
    public static final String SmsCodeLogin_URI = "/user/verifyLogin";
    public static final String[] WHITE_LIST = new String[]{
            //买家端公共访问接口
            "/buyer/*/common/**","/buyer/common/**","/seller/import/GetExcel",
            "/static", "/error", "/alipay", "/alipayAsyncHandle", "/websocket/{userId}",
            "/actuator/health", "/actuator/info", "/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**", "/swagger-resources/**",
            "/user/verify","/user/reset","/user/verifyLogin", "/user/login", "/user/register", "/user/sendMsg",
    };

    /**
     * 路径匹配方式
     */
    @Bean
    public AntPathMatcher antPathMatcher() {
        return new AntPathMatcher();
    }

    /**
     * SpringSecurity 跨域配置
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // configuration.setAllowedOrigins(List.of("http://127.0.0.1:8080", "http://127.0.0.1:8848"));
        configuration.setAllowedOriginPatterns(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    /**
     * 配置Security加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置Security授权规则
     */
    @Bean
    public SecurityFilterChain securityFilterChain(
            HttpSecurity http,
            SecurityAuthenticationAccessHandler securityAuthenticationAccessHandler,
            SecurityAuthenticationEntryPointHandler securityAuthenticationEntryPointHandler,
            SecurityLogoutSuccessHandler securityLogoutSuccessHandler,
            SecurityAccessDeniedHandler securityAccessDeniedHandler,
            SecurityJwtAuthenticationFilter securityJwtAuthenticationFilter,
            CustomAuthenticationProvider smsCodeAuthenticationProvider,
            CorsConfigurationSource corsConfigurationSource
    ) throws Exception {
        // 关闭表单的防伪造请求（在表单中默认携带一个随机token字符串），因为前后端分离没办法保证token
        http.csrf().disable();

        http.cors().configurationSource(corsConfigurationSource);

        // 退出策略
        http.logout(customizer -> customizer
                //.addLogoutHandler(securityLogoutHandler)
                .logoutSuccessHandler(securityLogoutSuccessHandler)
                .permitAll()
        );

        // 异常处理
        http.exceptionHandling(customizer -> customizer
                .authenticationEntryPoint(securityAuthenticationEntryPointHandler)
                .accessDeniedHandler(securityAccessDeniedHandler)
        );

        http.authorizeHttpRequests((authorize) -> authorize
                // 静态资源，无条件允许
                .requestMatchers(WHITE_LIST).permitAll()
                .requestMatchers("/hello").anonymous()
                //其他所有资源，通过自定义规则授权
                .anyRequest().access(securityAuthenticationAccessHandler::check)
        );

        //添加自定义认证过滤器
        http.addFilterBefore(securityJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .authenticationProvider(smsCodeAuthenticationProvider);

        // Session管理策略
        http.sessionManagement(customizer -> customizer
                .sessionCreationPolicy(SessionCreationPolicy.NEVER)
        );
        // 构造出SecurityFilterChain对象并返回
        return http.build();
    }
}
